<?php
namespace app\admin\business;
use app\common\model\mysql\AdminUser;
use think\Exception;

class  AdminUsers {

    /*
     * 登录与数据库的交互
     */
    public static function  login($data){
        try{
            $adminUserObj = new AdminUser();
            $adminData = self::getUserData($data['username']);
            if(!$adminData){
                throw  new Exception('用户不存在');
            }
            //处理密码
            if($adminData['password'] != md5($data['password'].'-singwa-abc')){
                throw  new Exception('密码不正确');
            }
            //更新数据表的数据
            $updateData = [
                'last_login_time'=>time(),
                'last_login_ip'=>request()->ip(),
                'update_time'=>time()
            ];
            $res = $adminUserObj->updateById($adminData['id'],$updateData);
            if(empty($res)){
                throw new Exception('登录失败');
            }
        } catch (\Exception $e){
            //记录日志 $e->getError();
            throw new Exception($e->getMessage());
        }
        //记录session信息
        session(config('admin.session_user'),$adminData);
        return true;
    }

    /*
     * 通过用户名获取用户信息
     * @param $username
     * @return array|bool|\think\Model|null
     */
    public static function getUserData($username){
        $adminUserObj = new AdminUser();
        $adminData = $adminUserObj->getAdminUserByUserName($username);
        if((empty($adminData))||($adminData->status != config('status.mysql.table_normal'))){
           return false;
        }
        $adminData = $adminData->toArray();
        return $adminData;
    }
}